package com.qzsoft.zhjd.common.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

public class ConvertUtils {
    private static final Logger logger = LoggerFactory.getLogger(ConvertUtils.class);

    public static <T> T sourceToTarget(Object source, Class<T> target) {
        if (source == null) {
            return null;
        }
        T targetObject = null;
        try {
            targetObject = target.newInstance();
            BeanUtils.copyProperties(source, targetObject);
        } catch (Exception e) {
            logger.error("convert error ", e);
        }
        return targetObject;
    }

    public static <T> List<T> sourceToTarget(Collection<?> sourceList, Class<T> target) {
        if (sourceList == null) {
            return null;
        }
        List<T> targetList = new ArrayList<>(sourceList.size());
        try {
            for (Object source : sourceList) {
                T targetObject = target.newInstance();
                BeanUtils.copyProperties(source, targetObject);
                targetList.add(targetObject);
            }
        } catch (Exception e) {
            logger.error("convert error ", e);
        }
        return targetList;
    }

    public static <T> IPage<T> sourceToTarget(IPage<?> sourcePage, Class<T> target) {
        if (sourcePage == null) {
            return null;
        }
        IPage<T> targetPage = new Page<T>();
        BeanUtils.copyProperties(sourcePage, targetPage, "records");
        List<?> sourceList = sourcePage.getRecords();
        if (null != sourceList) {
            List<T> targetList = sourceToTarget(sourceList, target);
            targetPage.setRecords(targetList);
        }
        return targetPage;
    }
}
